package com.xiaoxin.errorDemo.controller;

import com.xiaoxin.errorDemo.async.AsyncTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/async")
public class AsyncController {

    @Autowired
    private AsyncTask asyncTask;

    @GetMapping("/test01")
    public Map<String, Object> test01() {
        long begin = System.currentTimeMillis();
        asyncTask.task1();
        asyncTask.task2();
        asyncTask.task3();
        long end = System.currentTimeMillis();
        Map<String, Object> outMap = new HashMap<>();
        outMap.put("msg", "请求成功");
        outMap.put("耗时", end - begin);
        return outMap;
    }

    @GetMapping("/test02")
    public Map<String, Object> test02() {
        long begin = System.currentTimeMillis();
        Future<String> task4 = asyncTask.task4();
        Future<String> task5 = asyncTask.task5();
        String task4Result = "-";
        String task5Result = "-";

        for (; ; ) {
            if (task4.isDone() && task5.isDone()) {
                try {
                    task4Result = task4.get();
                    task5Result = task5.get();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                break;
            }
        }

        long end = System.currentTimeMillis();
        Map<String, Object> outMap = new HashMap<>();
        outMap.put("msg", "请求成功");
        outMap.put("耗时", end - begin);
        // ↓此时一定执行完了
        outMap.put("task4结果", task4Result);
        outMap.put("task5结果", task5Result);
        return outMap;
    }
}
